package com.atguigu.flink.watermark;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import com.atguigu.flink.utils.MyUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/4/8
 */
public class Demo2_EventTimeWindow
{
    public static void main(String[] args) throws Exception {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 3333);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        env.getConfig().setAutoWatermarkInterval(2000);
        env.disableOperatorChaining();
        env.setParallelism(1);

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner( (e, ts) -> e.getTs());


        env
            .socketTextStream("hadoop102", 8888)
            .map(new WaterSensorMapFunction())
            //产生了水印，向下游发送水印
            .assignTimestampsAndWatermarks(watermarkStrategy)
            /*
               窗口1 size:[0,4999]， slide:4999

               窗口2 size:[5000,9999],slide:9999

               数据如何进入窗口?
                    是eventtime，看数据的时间属性是否 符合窗口的 时间范围。
                    是processingTime，看数据到达开窗算子的物理时间，是否符合窗口的 时间范围

                 数据进入哪个窗口，和水印无关！

             */
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessAllWindowFunction<WaterSensor, String, TimeWindow>()
            {
                @Override
                public void process(Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {

                    out.collect(context.window() + ":" + MyUtil.parseToList(elements));

                }
            })
            .print();


            env.execute();

    }
}
